import { defineStore, storeToRefs } from 'pinia'
import { ref, watchEffect } from 'vue'
import { useCurrActStroe } from '@/stores/currActStore'
import { useAsyncAxios } from '@/utils/asyncFuncStore'
import { useTagsStore } from '@/stores/tagSelectorStore'
import type { Article, CardData } from '@/types/loginType'
export const useCardStore = defineStore('useCardStore', () => {
  // 当前登录的用户数据
  const { currUser } = storeToRefs(useCurrActStroe())
  // 选择的 tag
  const { dynamicTags } = storeToRefs(useTagsStore())
  // 选择的 clumns

  //   原数据
  const cardOrigin = ref<CardData[]>([])
  //   代理，显示的数据
  const cardData = ref<CardData[]>([])
  // 修改方法
  function assignCardOrigin(data: CardData[]) {
    cardOrigin.value = data
  }
  function assignCardData(data: CardData[]) {
    cardData.value = data
  }

  // 获取cardOrigin 的方法
  async function articleData() {
    const { getArticleData } = useAsyncAxios()
    return await getArticleData()
  }

  // 排序方法
  function cardSortAsHot() {
    cardData.value.sort((a: CardData, b: CardData) => {
      return b.views - a.views
    })
  }
  function cardSortAsTime() {
    cardData.value.sort((a: CardData, b: CardData) => {
      return b.time.localeCompare(a.time, 'zh-CN')
    })
  }
  function cardAsTitle() {
    cardData.value.sort((a: CardData, b: CardData) => {
      return a.title.localeCompare(b.title, 'zh-CN')
    })
  }

  // 其他组件
  // 当前浏览的文章
  const thisArt = ref<Article>({
    id: 'null',
    columnId: 'null',
    columnName: 'null',
    title: 'null',
    mainImg: 'null',
    content: [],
    authorId: 'null',
    authorName: 'null',
    authorImg: 'null',
    time: 'null',
    tag: ['null'],
    views: 0,
    followed: 0,
    isHeart: false
  })
  // 修改方法
  function assignThisArt(data: Article) {
    thisArt.value = data
  }
  // 异步获取数据,获取单篇文章数据
  async function idToArticleAndComments(id: string) {
    const { getArticle } = useAsyncAxios()
    return await getArticle(id)
  }

  // tag组件， card 的子组件
  // tag过滤方法
  const tagFilter = ref<CardData[]>([])
  watchEffect(() => {
    tagFilter.value = cardOrigin.value.filter((item) => {
      return dynamicTags.value.every((target) => item.tag.includes(target))
    })
    cardData.value = tagFilter.value
  })

  return {
    thisArt,
    cardOrigin,
    cardData,
    cardSortAsHot,
    cardSortAsTime,
    cardAsTitle,
    assignThisArt,
    idToArticleAndComments,
    assignCardData,
    assignCardOrigin,
    articleData
    // filterArticleData
  }
})
